package util;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

public class Log {
	
	private static String filePath = System.getProperty("user.dir")+"/test";
	private static String memLogFilePath = System.getProperty("user.dir")+"/mem_log_test";
	private final static String ext = ".txt"; 
	private static Map<String, String> memLog = new HashMap<String, String>(); 
	
	public static void debug(String message){
		
		if(Log.type.equals("F")){
			
			try {
				File f = new File(filePath + ext);
				FileWriter fw = new FileWriter(f,true);
				
				fw.write(message+"\n");
				fw.flush();
				fw.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		
		else{
		System.out.println(message);
		}
		
	}
	
	public static void debug(String key, String message) {
		String appendMessage = memLog.get(key);
		if(appendMessage != null) {
			appendMessage += message;
		} else {
			appendMessage = message;
		}
		
		memLog.put(key, appendMessage);
	}
	
	public static void debugln(String key, String message) {
		String appendMessage = memLog.get(key);
		if(appendMessage != null) {
			appendMessage += message;
		} else {
			appendMessage = message;
		}
		
		memLog.put(key, appendMessage + "\n");
	}
	
	public static String type = "C";
	public static void setType(String type){
		Log.type = type;
	}
	
	static {
		Runtime rt = Runtime.getRuntime();
		rt.addShutdownHook(new Thread() {
			@Override
			public void run() {
				if(memLog.size() == 0) return;
				
				File f = new File(memLogFilePath + ext);
				int fileIndex = 0;
				while(f.exists()) {
					f = new File(memLogFilePath + fileIndex++ + ext);
				}
				
				try {
					FileWriter fw = new FileWriter(f,true);
					Set<String> keyIterator = memLog.keySet();
					for(String key : keyIterator) {
						fw.write(key + "-log \n");
						fw.write(memLog.get(key) + "\n\n\n");
					}
					fw.flush();
					fw.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		});
	}

}
